<template>
	<view class="container">
		<tui-loading v-show="!pageData.loading"></tui-loading>
		<view class="page" v-show="pageData.loading" :style="{marginTop:header.init.height+'px'}">
			<!--header-->
			<tui-navigation-bar @init="initNavigation" @change="changeNavigation" :title="header.title" :color="tui.getColorSite().title.color" :backgroundColor="tui.getColorSite().title.backgroundColor" :splitLine="header.splitLine" :isOpacity="header.isOpacity" :maxOpacity="header.maxOpacity" :transparent="header.transparent" :scrollTop="header.scrollTop" :scrollRatio="header.scrollRatio" :isCustom="header.isCustom" :isImmersive="header.isImmersive" :isFixed="header.isFixed" :backdropFilter="header.backdropFilter" :dropDownHide="header.dropDownHide" :zIndex="header.zIndex">
				<view class="tui-header-icon" :style="{top:header.init.top+'px'}">
					<tui-icon name="arrowleft" :color="tui.getColorSite().title.color" @click="back"></tui-icon>
				</view>
			</tui-navigation-bar>
			<!--header-->
			<view style="padding: 0 0 118rpx 0;box-sizing: border-box;">
				<tui-form-item padding="45rpx 25rpx" left="0" right="0" arrow borderColor="#F1F1F1" @click="detail('chooseAddr')">
					<view class="tui-address">
						<view v-if="param.address_id > 0 && pageData.cacheData.address">
							<view class="tui-userinfo">
								<text class="tui-name">{{pageData.cacheData.address.full_name}}</text> {{tui.formatNumber(pageData.cacheData.address.phone)}}
							</view>
							<view class="tui-addr">
								<view class="tui-addr-tag" v-if="pageData.cacheData.address.is_default === 1">默认</view>
								<text>{{pageData.cacheData.address.province}}{{pageData.cacheData.address.city}}{{pageData.cacheData.address.district}}{{pageData.cacheData.address.info}}</text>
							</view>
						</view>
						<view class="tui-none-addr" v-else>
							<image :src="appInit.image.address_position" class="tui-addr-img" mode="widthFix" v-if="appInit.image"></image>
							<text>新增收货地址</text>
						</view>
					</view>
					<view class="tui-address-bg-img"></view>
				</tui-form-item>
				<view class="tui-goods-info">
					<tui-form-item padding="26rpx 30rpx 0 30rpx" left="0" right="0" borderColor="#F1F1F1">
						<view class="tui-goods-title">
							商品信息
						</view>
					</tui-form-item>
					<tui-form-item left="0" right="0" borderColor="#F1F1F1" v-for="(item,index) in pageData.listData" :key="index" v-if="tui.inArray(pageData.cacheData.type,['cart'])">
						<view class="tui-goods-item">
							<image :src="item.obj_info.picture.url" class="tui-goods-img"></image>
							<view class="tui-goods-center">
								<view class="tui-goods-name">
									<tui-overflow-hidden :lineClamp="2">
										{{item.obj_info.title}}
									</tui-overflow-hidden>
								</view>
								<view class="tui-goods-attr" v-if="item.obj_info.keys">
									<tui-tag type="danger" size="20rpx" plain padding="10rpx 10rpx" v-for="(keysItem,keysIndex) in item.obj_info.keys" :key="keysIndex">{{keysItem}}</tui-tag>
								</view>
							</view>
							<view class="tui-price-right" style="color: red;">
								<view>
									<text>￥{{item.price}}</text>
									<text v-if="item.integral>0">+{{ item.integral }}积分</text>
								</view>
								<view style="margin-top: 10rpx;">x{{item.num}}</view>
							</view>
						</view>
					</tui-form-item>
					<tui-form-item left="0" right="0" borderColor="#F1F1F1" v-if="tui.inArray(pageData.cacheData.type,['buy'])">
						<view class="tui-goods-item" v-if="pageData.cacheData.info">
							<image :src="pageData.cacheData.info.thumb.url" class="tui-goods-img"></image>
							<view class="tui-goods-center">
								<view class="tui-goods-name">
									<tui-overflow-hidden :lineClamp="2">
										{{pageData.cacheData.info.title}}
									</tui-overflow-hidden>
								</view>
							</view>
							<view class="tui-price-right" style="color: red;">
								<view>￥{{pageData.cacheData.info.current_price}}</view>
								<view>x{{pageData.cacheData.data.num}}</view>
							</view>
						</view>
					</tui-form-item>
					<tui-input label="订单备注" :lineLeft="false" type="text" :labelSize="28" :size="28" clearable placeholder="选填: 请输入订单备注..." v-model="param.remarks" confirmType="done"></tui-input>

					<tui-form-item left="0" right="0" borderColor="#F1F1F1">
						<view class="flex-b tui-size-28" style="justify-content: flex-end;">
							<view class="flex tui-flex-end tui-color-red">
								<view style="color: #222;line-height: 30rpx;">共</view>
								<view class="tui-price-large">{{pageData.totalNum}}</view>
								<view style="color: #222;line-height: 30rpx;">件，</view>
								<view style="color: #222;line-height: 30rpx;">合计： </view>
								<view class="tui-size-26">￥</view>
								<view class="tui-price-large">{{pageData.totalPrice}}</view>
							</view>
						</view>
					</tui-form-item>
				</view>
			</view>

			<t-pay-way :price="pageData.payWay.price" :paySite="pageData.payWay.paySite" :show="pageData.payWay.status" @btnPay="btnPay" @close="payWayClose"></t-pay-way>


			<view class="tui-operation" style="justify-content: flex-end;">
				<view class="flex tui-flex-end" style="color: #E41F19;padding-right: 30rpx;padding-right: 20rpx;">
					<view style="color: #222;line-height: 30rpx;">实付金额: </view>
					<view class="tui-size-26">￥</view>
					<view class="tui-price-large">{{pageData.totalPrice}}</view>
				</view>
				<view class="tui-pr25">
					<view class="flex-b tui-size-28">
						<tui-button width="200rpx" height="70rpx" :size="28" type="danger" shape="circle" @click="detail('payWay')">确认支付</tui-button>
					</view>
				</view>
			</view>
			<view class="tui-safearea-bottom"></view>
		</view>
	</view>
</template>

<script>
	import formCheck from "@/components/common/tui-validation/tui-validation.js"
	import tPayWay from "@/components/views/t-pay-way/t-pay-way"
	export default {
		components: {
			tPayWay,
		},
		data() {
			return {
				get: {},
				header: {
					title: '测试首页', //NavigationBar标题
					splitLine: true, //是否需要分割线
					isOpacity: false, //是否设置不透明度
					maxOpacity: 1, //不透明度最大值 0-1
					transparent: false, //背景透明 （设置该属性，则背景透明，只出现内容，isOpacity和maxOpacity失效）
					scrollTop: 0, //滚动条滚动距离
					scrollRatio: 0.3, //isOpacity 为true时生效（opacity=scrollTop /windowWidth * scrollRatio）
					isCustom: false, //是否自定义NavigationBar内容
					isImmersive: true, //是否沉浸式,
					isFixed: true, //是否固定
					backdropFilter: false, //是否开启高斯模糊效果[仅在支持的浏览器有效果]，为true时maxOpacity设置小于1的值
					dropDownHide: false, //下拉隐藏NavigationBar，主要针对有回弹效果ios端
					zIndex: 9998, //z-index值
					init: {
						width: 0,
						height: 0,
						left: 0,
						top: 0,
						scrollH: 0,
					},
				},
				pageData: {
					loading: false,
					cacheData: {},
					totalPrice: 0,
					totalNum: 0,
					listData: [],
					payWay: {
						status: false,
						price: '0',
						paySite: {},
					},
				},
				param: {
					address_id: 0,
					remarks: '',
				},
				xhrUrl: '/goods',
				appInit: {},
				user: {},
			}
		},
		// 监听页面加载，其参数为上个页面传递的数据，参数类型为 Object（用于页面传参）
		onLoad(e) {
			let that = this;
			// uni.startPullDownRefresh();
			console.log("self:onLoad++++++++++++++++++++++++++++++++++++++++++++++++++");
			uni.stopPullDownRefresh(); //停止当前页面下拉刷新
			if (typeof(e.scene) != 'undefined') {
				e = that.tui.getUrlkey(decodeURIComponent(e.scene));
			}
			that.get = e;
			if (typeof that.get.title !== 'undefined') {
				that.header.title = that.get.title;
				if (that.header.title.length > 13) {
					that.header.title = that.header.title.slice(0, 13) + '...';
				}
				that.$forceUpdate();
			}
			console.log("self:getData=>", that.get);
			let obj = {};
			uni.getSystemInfo({
				success: function(res) {
					that.header.init.width = obj.left || res.windowWidth;
					that.header.init.height = obj.top ? obj.top + obj.height + 8 : res.statusBarHeight + 44;
					that.header.init.top = obj.top ? obj.top + (obj.height - 32) / 2 : res.statusBarHeight + 6;
					that.header.init.scrollH = res.windowWidth * 0.6;
					that.header.init.scrollH = res.windowWidth * 1;
				}
			});
			that.$forceUpdate();
			that.initialize();
		},
		// 监听页面显示。页面每次出现在屏幕上都触发，包括从下级页面点返回露出当前页面
		onShow() {
			let that = this;
			that.uppPage();
		},
		// 监听页面滚动，参数为Object
		onPageScroll(e) {
			let that = this;
			that.header.scrollTop = e.scrollTop;
			that.$forceUpdate();
		},
		methods: {
			uppPage() {
				let that = this;
				that.param.address_id = 0;
				that.pageData.cacheData.address = {};
				let lastUppAddressData = that.tui.getCache('lastUppAddressData');
				if (lastUppAddressData !== false) {
					if (
						typeof lastUppAddressData.id !== 'undefined' &&
						typeof lastUppAddressData.member_id !== 'undefined' &&
						typeof that.user !== 'undefined' &&
						typeof that.user.userInfo !== 'undefined' &&
						lastUppAddressData.member_id === that.user.userInfo.id &&
						true
					) {
						that.pageData.cacheData.address = lastUppAddressData;
						that.param.address_id = lastUppAddressData.id;
					}
				}
				that.$forceUpdate();
				that.pageData.loading = true;
			},
			initialize() {
				let that = this;
				let Int = setInterval(function() {
					that.user = that.tui.getCache("user");
					console.log('self:user=>', that.user);
					if (typeof(that.user) == 'object') {
						clearInterval(Int);
						that.__init();
					}
				}, 800);
			},
			async __init() {
				let that = this;
				that.appInit = that.tui.getCache("appInit");
				console.log('self:appInit=>', that.appInit);
				that.pageData.cacheData = that.tui.getCache('goodsBuyCache');
				if (that.tui.isDebug()) {
					that.param.remarks = that.tui.formatDate().format;
				}
				switch (that.pageData.cacheData.type) {
					case 'cart':
						that.param.cart_id = that.pageData.cacheData.id;
						let cartList = await that.tui.get('/goods', {
							cart: that.tui.formatDate().timestamp,
							cart_id: that.tui.arr2str(that.pageData.cacheData.id, ','),
						});
						that.pageData.listData = cartList.data.data;
						let cartTotalPrice = 0;
						let cartTotalPriceSum = 0;
						let cartTotalIntegral = 0;
						let cartTotalNum = 0;
						that.pageData.listData.forEach(function(item, k) {
							cartTotalPrice += item.price * item.num;
							cartTotalPriceSum += item.price * item.num;
							cartTotalIntegral += item.integral * item.num;
							cartTotalNum += item.num;
						})
						that.pageData.totalPrice = (cartTotalPrice * 100 / 100).toFixed(2);
						that.pageData.totalPriceSum = (cartTotalPriceSum * 100 / 100).toFixed(2);
						that.pageData.totalIntegral = cartTotalIntegral;
						that.pageData.totalNum = cartTotalNum;
						break;
					case 'buy':
						let buyTotalPrice = 0;
						let buyTotalNum = 0;
						buyTotalPrice = that.pageData.cacheData.info.current_price * that.pageData.cacheData.data.num;
						buyTotalNum = that.pageData.cacheData.data.num;
						that.pageData.totalPrice = (buyTotalPrice * 100 / 100).toFixed(2);
						that.pageData.totalNum = buyTotalNum;
						that.param.obj_id = that.pageData.cacheData.data.obj_id;
						that.param.sku = that.pageData.cacheData.data.sku;
						that.param.num = that.pageData.cacheData.data.num;
						break;
				}
				that.pageData.payWay.price = that.pageData.totalPrice;
				let index = 0;
				for (let item in that.appInit.paySite) {
					that.appInit.paySite[item].info = '';
					switch (that.appInit.paySite[item].field || 'other') {
						case "u_species":
							if (that.user.userInfo.u_species * 100 < that.pageData.payWay.price / that.tui.str2arr(that.appInit.integral2u_species, ':')[1]) {
								that.appInit.paySite[item].info = 'U币不足';
							} else {
								that.appInit.paySite[item].info = 'U币支付≈' + that.pageData.payWay.price / that.tui.str2arr(that.appInit.integral2u_species, ':')[1];
							}
							break;
					}
					console.log(that.appInit.paySite);
					if (that.tui.inArray(index, [0])) {
						that.appInit.paySite[item].status = true;
					} else {
						that.appInit.paySite[item].status = false;
					}
					index++;
				}
				that.pageData.payWay.paySite = that.appInit.paySite;
				that.uppPage();
			},
			payWayClose() {
				let that = this;
				that.pageData.payWay.status = false;
			},
			async btnPay(e) {
				let that = this;
				that.param.pay_fun = e.payKey;
				that.param.ambient = 0;
				switch (e.payKey) {
					case -1:
						that.tui.toast("请选择付款方式", false, function() {}, 1500);
						return;
					case 2:
					case 3:
						console.log(that.param);
						return;
				}
				let response = await that.tui.post(that.xhrUrl, that.param, {
					pay: that.tui.formatDate().timestamp,
				}, true, true, false);
				that.tui.toast(response.info, false, function() {
					switch (response.status) {
						case 0:
							that.tui.setUserInfo(response.data.userInfo, function(response) {
								that.tui.urlTab('/pages/index-index');
							});
							break;
						default:
							break;
					}
				}, 1500);
			},
			async detail(type, item = {}) {
				let that = this;
				switch (type) {
					case 'chooseAddr':
						switch (typeof that.user.userAddress.id) {
							case 'undefined':
								that.tui.urlHref('/pages/public-form?' + that.tui.initParamsData({
									title: '新增地址',
									tpl: 'address',
									retreat: 1,
									callback: 'cart',
									address_id: 0,
									timestamp: that.tui.formatDate().timestamp
								}));
								break;
							case 'number':
								that.tui.urlHref('/pages/public-list?' + that.tui.initParamsData({
									title: '选择收货地址',
									tpl: 'address',
									isSelect: that.tui.formatDate().timestamp,
									timestamp: that.tui.formatDate().timestamp
								}));
								break;
							default:
								console.log(typeof that.user.userAddress.id);
								break;
						}
						break;
					case 'payWay':
						if (that.tui.inArray(that.param.address_id, [0])) {
							that.tui.toast("请先添加收货地址", false, function() {}, 1500);
							return;
						}
						that.pageData.payWay.status = true;
						break;
					default:
						break;
				}
				// that.tui.urlHref(item.url + '?' + that.tui.initParamsData(item.param || {
				// 	timestamp: that.tui.formatDate().timestamp
				// }));
			},
			initNavigation(e) {
				let that = this;
				that.header.opacity = e.opacity;
				that.header.top = e.top;
				that.$forceUpdate();
			},
			changeNavigation(e) {
				let that = this;
				that.header.opacity = e.opacity;
				that.$forceUpdate();
			},
			back() {
				let that = this;
				that.tui.urlBack(1);
			},
		},
		// 页面滚动到底部的事件（不是scroll-view滚到底），常用于下拉下一页数据
		onReachBottom() {
			let that = this;
		},
		// 监听页面隐藏
		onHide() {
			let that = this;
		},
		// 监听页面卸载
		onUnload() {
			let that = this;
		},
		// 页面返回
		onBackPress() {
			let that = this;
		},
		// #ifdef MP
		onShareAppMessage() {
			// console.log('分享!')
		},
		// #endif
	}
</script>

<style scoped lang="scss">
	.tui-address {
		min-height: 80rpx;
		padding: 10rpx 0;
		box-sizing: border-box;
		position: relative;

		.tui-userinfo {
			font-size: 30rpx;
			font-weight: 500;
			line-height: 30rpx;
			padding-bottom: 12rpx;

			.tui-name {
				padding-right: 40rpx;
			}
		}

		.tui-addr {
			font-size: 24rpx;
			word-break: break-all;
			padding-right: 25rpx;

			.tui-addr-tag {
				padding: 5rpx 8rpx;
				flex-shrink: 0;
				background: #EB0909;
				color: #fff;
				display: inline-flex;
				align-items: center;
				justify-content: center;
				font-size: 25rpx;
				line-height: 25rpx;
				transform: scale(0.8);
				transform-origin: 0 center;
				border-radius: 6rpx;
			}
		}

		.tui-none-addr {
			height: 80rpx;
			padding-left: 5rpx;
			display: flex;
			align-items: center;

			.tui-addr-img {
				width: 36rpx;
				height: 46rpx;
				display: block;
				margin-right: 15rpx;
			}
		}
	}

	.tui-goods-info {
		.tui-goods-title {
			font-size: 28rpx;
			display: flex;
			align-items: center;
		}

		.tui-goods-item {
			width: 100%;
			box-sizing: border-box;
			display: flex;
			justify-content: space-between;

			.tui-goods-img {
				width: 180rpx;
				height: 180rpx;
				display: block;
				flex-shrink: 0;
			}

			.tui-goods-center {
				flex: 1;
				padding: 0 20rpx;
				box-sizing: border-box;
				display: flex;
				flex-direction: column;
				justify-content: space-between;

				.tui-goods-attr {
					padding-top: 20rpx;
					width: 80%;
				}
			}

			.tui-price-right {
				text-align: right;
				color: #888888;
				line-height: 30rpx;
				padding-top: 20rpx;
			}
		}
	}
</style>